package com.by;

import com.rabbitmq.client.*;

import java.io.IOException;
import java.util.concurrent.TimeoutException;


public class ConsumerTwo {
    public static void main(String[] args) throws IOException, TimeoutException {
        //1. 创建连接  实例化连接工场
        ConnectionFactory factory = new ConnectionFactory();
        //设置服务器地址
        factory.setHost("192.168.131.128");//默认是localhost
        //设置账号
        factory.setUsername("admin");//默认是guest
        factory.setPassword("123456");//默认是guest
        //设置端口号
        factory.setPort(5672);//默认是5672
        //设置虚拟主机
        factory.setVirtualHost("/");//默认值是  /

        //2.创建连接
        Connection conn = factory.newConnection();

        //3.创建信道
        Channel channel = conn.createChannel();

        //4.声明队列
        String queueName = "work";//队列名称
        /**
         * queue  队列的名称
         * durable  队列是否持久 化   true持久化 false非
         * exclusive 是否独占连接
         * autoDelete 是否自动删除  长时间不再使用的队列
         * arguments 附加参数
         */
        channel.queueDeclare(queueName, false, false, false, null);

        System.out.println("消息者Two开始读取消息:");

        //消费者获取队列的消息
        //channel.basicConsume(queueName,true,(consumerTag, message) -> {},consumerTag->{});
        //消息投递回调
        DeliverCallback deliverCallback = (consumerTag, message) -> {
            //读取队列中的消息
            String msg = new String(message.getBody());
            System.out.println("消费者Two正在消费"+msg);
            doWork(msg);
            System.out.println("消费者Two消费完"+msg);
        };
        //取消回调
        CancelCallback cancelCallback = consumerTag -> {
        };

        channel.basicConsume(queueName, true, deliverCallback, cancelCallback);


        //不能关闭连接  消费者消费完处于阻塞状态   有消息会接着消费


    }
        static void doWork(String msg){
        for(int i=0; i<msg.length(); i++){
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
        }




    }
}
